package com.dave.admin.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dave.admin.common.base.BaseEntity;
import com.dave.admin.modular.boss.entity.UserAdmin;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 封装对象自动拼接条件工具
 */
public abstract class QueryWrapperUtil {


    public static QueryWrapper getQueryWrapper(Object object) {
        return getQueryWrapper(new QueryWrapper(), object);
    }

    public static QueryWrapper getQueryWrapper(Object object, String... exclude) {
        return getQueryWrapper(new QueryWrapper(), object, exclude);
    }

    public static QueryWrapper getQueryWrapper(QueryWrapper queryWrapper, Object object) {
        return getQueryWrapper(queryWrapper, object, new String[]{});
    }


    public static QueryWrapper getQueryWrapper(QueryWrapper queryWrapper, Object object, String... exclude) {
        Class clazz = object.getClass();
        Field[] fields = ReflectUtil.getFields(clazz);
        if (ArrayUtil.isNotEmpty(fields)) {
            for (Field field : fields) {
                field.setAccessible(true);

                //静态变量 不做为条件
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }
                //排除Mybatis plus 注解不存在的字段
                if (field.getAnnotation(TableField.class) != null && !field.getAnnotation(TableField.class).exist()) {
                    continue;
                }

                Object value = ReflectionUtils.getField(field, object);

                //特殊类型预处理  还是有点问题
                if (value instanceof LocalDateTime) {
                    value = DateUtil.parse(value.toString().replaceAll("T", " ")).toString();
                }


                if (Objects.nonNull(value) && StringUtils.isNotBlank(value.toString()) && !ArrayUtil.contains(ArrayUtil.append(new String[]{"pageIndex", "pageSize"}, exclude), field.getName())) {
                    if (ArrayUtil.contains(new String[]{StrUtil.toCamelCase(UserAdmin.NICK_NAME),
                            BaseEntity.NAME,BaseEntity.CREATE_TIME}, field.getName())) { //需要模糊查询字段
                        queryWrapper.like(StrUtil.toUnderlineCase(field.getName()), value.toString());
                    } else {
                        queryWrapper.eq(StrUtil.toUnderlineCase(field.getName()), value);
                    }
                }
            }
        }
        return queryWrapper;
    }
}
